// 内置模块
const fs = require('fs')
const http = require('http')
const url = require('url')

// 外部模块
const marked = require('marked')

const server = http.createServer()
server.on('request', (request, response) => {

    if (request.url == "/favicon.ico") return

    // 读取 README.md
    fs.readFile('./README.md', 'utf8', (err, mdStr) => {
        if (err) {
            throw err
        }
        // 读取 ./template.html
        fs.readFile('./template.html', 'utf8', (err, tmpStr) => {
            if (err) {
                throw err
            }
            // 将template.html 中的code替换成 README.md中的文件
            const html = tmpStr.replace('Talk is cheap. Show me the code', marked(mdStr))
            // 将替换后的HTML写入到 README.html
            fs.writeFile('README.html', html, err => {
                if (err) {
                    throw err
                }

                const pathName = url.parse(request.url, true).pathname
                const filePath = `.${request.url}`

                // 请求路径以/node_modules/ 和 /style/ 开始 读取请求文件返回 否则读取 README.html
                if (pathName.startsWith('/node_modules/') || pathName.startsWith('/src/')) {

                    fs.readFile(`.${pathName}`, (err, data) => {
                        if (err) {
                            throw err
                        }
                        response.end(data)
                    })
                } else if (pathName == '/') {

                    fs.readFile('./README.html', 'utf8', (err, data) => {
                        if (err) {
                            throw err
                        }
                        console.log(`用户IP:${request.connection.remoteAddress}正在访问...`)
                        response.end(data)
                    })
                } else {
                    return response.end('404 Not Found')
                }
            })
        })
    })
})

server.listen('8888','0.0.0.0', () => {
    console.log('server is running at port 8888')
})